<?php
namespace application\common\controller;
use application\common\model\User;
use think\Controller;
use think\exception\HttpException;
use think\Session;
use application\common\controller\Tools;

/**
 * Class Base
 * @package application\index\controller
 * @Auth wp
 * @describe 基础公共类
 */
class Base extends Controller
{
    public function _initialize() {
        parent::_initialize();
        if (! Session::get('userName')) {
//            if (! preg_match('#exam.pgbkb.top#', $_SERVER['HTTP_HOST'])) {
//                $this->redirect('http://exam.pgbkb.top');
//            }
            $this->redirect('index/index/index');
        }
    }
    public function logout() {
        Session::clear();
        $this->redirect('index/index/index');
    }
    public function modifyPassword() {
        if (! $this->request->isPost()) {
            throw new HttpException('403');
        }else {
            $oldPassword = $this->request->post('oldPassword');
            $newPassword = $this->request->post('newPassword');
            if (empty($oldPassword) || empty($newPassword)) {
                $this->error("请输入完整您的旧密码和新密码！",$_SERVER['HTTP_REFERER']);
            }else {
                $tools = new Tools();
                if ($tools->checkPassword($newPassword)) {
                    $user = new User();
                    $userPassword = $user->where('user_id',Session::get('userId'))->column('user_password')[0];
                    if (md5($oldPassword) != $userPassword) {
                        $this->error("您的密码输入错误，请输入正确的旧密码！",$_SERVER['HTTP_REFERER']);
                    }else {
                        $user->save(['user_password' => md5($newPassword)],['user_id' => Session::get('userId')]);
                        Session::destroy();
                        $this->success("修改密码成功，请重新登录！",'index/index/login');
                    }
                }
            }
        }
    }
}